package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    ApArticleMapper apArticleMapper;
//    @Autowired
//            @Qualifier
    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
      //获取模板
        try {
            Template template = configuration.getTemplate("article.ftl");
            //准备数据
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            Integer userId = apAuthor.getUserId();
            System.out.println("content = " + content + ", apArticle = " + apArticle);
            System.out.println("===============>"+apArticle.getAuthorName());
            Map dataModel = new HashMap<>();
            dataModel.put("authorApUserId",userId);
            dataModel.put("article",apArticle);
            dataModel.put("content", JSONArray.parseArray(content,Map.class));

            //用数据替换模板， 输出到指定的输出流中
            StringWriter writer = new StringWriter();
            template.process(dataModel,writer);
            String contentHtml = writer.toString();

            //将静态也 上传到minIO中
            InputStream is = new ByteArrayInputStream(contentHtml.getBytes());
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", is);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("文章详情静态页生成成功 staticUrl=====> {}", path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败 当前文章信息：{}" ,apArticle);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }

        //准备数据

      //用数据替换模板，输出到指定的输出流
    }
}
